"""
改编自我从前写的malody解析代码
不过基本没有优化过代码
使用了deraium在github上发布的osu2mc库:
    https://github.com/deraium/osu2mc/pulls
"""
import core
import json
import beat2time
import osu2mc.convert
import os
import re


def mc2map(path):
    C0EventDict = []
    C1EventDict = []
    C2EventDict = []
    C3EventDict = []

    with open(path, 'r', encoding="utf-8") as f:
        beatmap = json.load(f)

    title = beatmap['meta']['song']['title']
    # print("title:", title)
    # BPM = beatmap['time'][0]['bpm']
    notes = beatmap['note'][:-1]

    beat2time.load(beatmap['time'])

    for note in notes:
        column = note['column']
        beat = note['beat']
        time = beat2time.b2t(beat[0] + (beat[1] / beat[2]))

        if column == 0:
            C0EventDict.append(time)
        elif column == 1:
            C1EventDict.append(time)
        elif column == 2:
            C2EventDict.append(time)
        else:
            C3EventDict.append(time)

    newMap = []
    for time in sorted(list(set(C0EventDict + C1EventDict + C2EventDict + C3EventDict))):
        # print(time)
        newMap.append([0] * core.KEY.value['key'])
        if time in C0EventDict:
            newMap[-1][0] = 1
        if time in C1EventDict:
            newMap[-1][1] = 1
        if time in C2EventDict:
            newMap[-1][2] = 1
        if time in C3EventDict:
            newMap[-1][3] = 1

    return newMap
    # return C0EventDict, C1EventDict, C2EventDict, C3EventDict


def osu2map(path):
    matched = re.match(r"(.+)\.(.+)", path)
    name = matched.group(1)
    osu2mc.convert.convert(path)    # 产生文件 name.mc
    if os.path.exists(name+".json"):
        os.remove(name+".json")
    os.rename(name+".mc", name+".json")

    newMap = mc2map(name+".json")
    # os.remove(name+".json")
    return newMap


def file2map(path):
    matched = re.match(r"(.+)\.(.+)", path)
    filetype = matched.group(2).lower()
    if filetype == "osu":
        return osu2map(path)
    elif filetype == "json" or filetype == "mc":
        return mc2map(path)


if __name__ == '__main__':
    print(mc2map('1.mc'))

